//
//  BHLazyManager.m
//  XNBeeHive
//
//  Created by xn on 2022/1/4.
//

#import "BHLazyManager.h"
#import "BHContext.h"
#import "BHModuleManager.h"

@interface BHLazyManager ()

@property (nonatomic, strong) NSArray *moduleClasses;
@property (nonatomic, strong) NSArray *serviceClasses;

@property (nonatomic, assign) BOOL hasLoadFile;

@end

@implementation BHLazyManager

+ (void)load {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[self sharedManager] loadLazyFile];
    });
}

+ (instancetype)sharedManager
{
    static id sharedManager = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}

- (void)loadLazyFile {
    {
        NSString *moduleConfigName = [BHContext shareInstance].lazy_moduleConfigName;
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:moduleConfigName ofType:@"plist"];
        if (plistPath.length >0){
            NSDictionary *moduleList = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
            NSArray<NSDictionary *> *modulesArray = [moduleList objectForKey:@"moduleClasses"];
            self.moduleClasses = modulesArray;
        }
        if (self.moduleClasses.count >0) {
            for (NSDictionary *item in self.moduleClasses) {
                NSString *clsName = [item objectForKey:@"moduleClass"];
                if (clsName.length >0 && NSClassFromString(clsName)) {
                    [[BHModuleManager sharedManager] registerDynamicModule:NSClassFromString(clsName) shouldTriggerInitEvent:YES];
                }
            }
        }
    }
    {
        NSString *serviceConfigName = [BHContext shareInstance].lazy_serviceConfigName;
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:serviceConfigName ofType:@"plist"];
        if (plistPath.length >0) {
            self.serviceClasses = [[NSArray alloc] initWithContentsOfFile:plistPath];
        }
    }
    self.hasLoadFile = YES;
}

- (Class)getIMPWithService:(Protocol*)service serviceName:(NSString *)serviceName;
{
    if (!service || serviceName.length <=0) return nil;
    if (!self.hasLoadFile) {
        [self loadLazyFile];
    }
    
    Class imp = [[BHServiceManager sharedManager] serviceImplClass:service];
    if (imp) return imp;
    for (NSDictionary *item in self.serviceClasses) {
        NSString *pro_name = [item objectForKey:@"service"];
        if ([NSStringFromProtocol(service) isEqualToString:pro_name]) {
            NSString *imp_name = [item objectForKey:@"impl"];
            [[BHServiceManager sharedManager] registerService:service implClass:NSClassFromString(imp_name)];
            return [[BHServiceManager sharedManager] serviceImplClass:service];
            break;
        }
    }
    return nil;
}

@end
